package com.site.core.spin;

import java.io.ByteArrayInputStream;

import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang.StringUtils;
 
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.cnc.bas.util.Log;
 
import com.site.util.HttpUtil;

public class Thebestspinner {
	
	protected static Log log = Log.getLogger(Thebestspinner.class);
	
	private static String url = "http://thebestspinner.com/api.php";
	
	private static String user = "heiblog@hotmail.com";
	private static String password = "b85d04827b51c248b35c7f58ca0dbd14";
	
	private static final String XML_FLAG = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	
	// 每个单词的最大同义词数
	private static int MAX_SYNS = 4;
	
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_SESSION = "session";
	private static final String TAG_OUTPUT = "output";
	
	// 质量
	public static final String QUALITY_GOOD = "1";
	public static final String QUALITY_BETTER = "2";
	public static final String QUALITY_BEST = "3";
	
	
	private String sessionId = null;
	
	public Thebestspinner(){
		init();
	}
	
	/**
	 * 初始化用户名、密码等
	 */
	public void init(){
		// 获取sessionId
		authenticate();
	}
	
	public static String spin(String content){
		return null;
	}
	
	/**
	 * 获取sessionId
	 */
	private void authenticate(){
		NameValuePair[] pairs = new NameValuePair[4];
		pairs[0] = new NameValuePair("action", "authenticate");
		pairs[1] = new NameValuePair("format", "xml");
		pairs[2] = new NameValuePair("username", user);
		pairs[3] = new NameValuePair("password", password);
		try{
			String content = HttpUtil.doGet(url, pairs);
			sessionId = genSessionId(content);
			log.logInfo("sessionId:" + sessionId + ".");
		}
		catch(Exception e){
			log.logError("authenticate exception:" + e.getMessage(), e);
		}
		
	}
	
	/**
	 * 识别同义词
	 * @param content
	 * @param protectedTerms
	 * @return
	 */
	public String identifySynonyms(String content, String protectedTerms){
		NameValuePair[] pairs = new NameValuePair[6];
		pairs[0] = new NameValuePair("action", "identifySynonyms");
		pairs[1] = new NameValuePair("format", "xml");
		pairs[2] = new NameValuePair("text", content);
		pairs[3] = new NameValuePair("maxsyns", String.valueOf(MAX_SYNS));
		pairs[4] = new NameValuePair("protectedTerms", protectedTerms);
		pairs[5] = new NameValuePair("session", sessionId);
		try{
			String result = HttpUtil.doGet(url, pairs);
			Document document = buildContent(result);
			if(document == null){
				log.logError("session id get fail!");
				return null;
			}
			Element root = document.getRootElement();
			String success = root.getChildTextTrim(TAG_SUCCESS);
			if("true".equals(success)){
				return root.getChildTextTrim(TAG_OUTPUT);
			}
		}
		catch(Exception e){
			log.logError("identifySynonyms exception:" + e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * spin
	 * @param content
	 * @param protectedTerms
	 * @return
	 */
	public String replaceEveryonesFavorites(String content, String protectedTerms, String quality){
		NameValuePair[] pairs = new NameValuePair[7];
		pairs[0] = new NameValuePair("action", "replaceEveryonesFavorites");
		pairs[1] = new NameValuePair("format", "xml");
		pairs[2] = new NameValuePair("text", content);
		pairs[3] = new NameValuePair("maxsyns", String.valueOf(MAX_SYNS));
		pairs[4] = new NameValuePair("quality", quality);
		pairs[5] = new NameValuePair("protectedTerms", protectedTerms);
		pairs[6] = new NameValuePair("session", sessionId);
		try{
			String result = HttpUtil.doGet(url, pairs);
			Document document = buildContent(result);
			if(document == null){
				log.logError("session id get fail!");
				return null;
			}
			Element root = document.getRootElement();
			String success = root.getChildTextTrim(TAG_SUCCESS);
			if("true".equals(success)){
				return root.getChildTextTrim(TAG_OUTPUT);
			}
		}
		catch(Exception e){
			log.logError("authenticate exception:" + e.getMessage(), e);
		}
		return null;
	}
	
	/**
	 * 获取sessionId
	 * @param content
	 * @return
	 */
	private String genSessionId(String content){
		Document document = buildContent(content);
		if(document == null){
			log.logError("session id get fail!");
			return null;
		}
		Element root = document.getRootElement();
		String success = root.getChildTextTrim(TAG_SUCCESS);
		if("true".equals(success)){
			return root.getChildTextTrim(TAG_SESSION);
		}
		
		return null;
	}
	
	/**
	 * 构造内容为document对象
	 * @param content
	 * @return
	 */
	private Document buildContent(String content){
		if(StringUtils.isEmpty(content)){
			return null;
		}
		try{
			String data = XML_FLAG + content;
			ByteArrayInputStream bais = new ByteArrayInputStream(data.trim().getBytes());
			SAXBuilder builder = new SAXBuilder();
			return builder.build(bais);
		}
		catch(Exception e){
			log.logError("buildContent [" + content + "] exception:" + e.getMessage(), e);
		}
		return null;
	}
	
	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}
	
	/**
	 * 查询还可以使用的次数
	 */
	public long apiQuota(){
		NameValuePair[] pairs = new NameValuePair[2];
		pairs[0] = new NameValuePair("action", "apiQuota");
		pairs[1] = new NameValuePair("session", sessionId);
		try{
			String result = HttpUtil.doGet(url, pairs);
			Document document = buildContent(result);
			if(document == null){
				log.logError("session id get fail!");
				return -1;
			}
			Element root = document.getRootElement();
			String success = root.getChildTextTrim(TAG_SUCCESS);
			if("true".equals(success)){
				return Long.parseLong(root.getChildTextTrim(TAG_OUTPUT));
			}	 
		}
		catch(Exception e){
			log.logError("authenticate exception:" + e.getMessage(), e);
		}
		return -1;
		
	}

	public static void  main(String[] args){
		Thebestspinner spin = new Thebestspinner();
		String sessionId = spin.getSessionId();
		System.out.println("sessionId:" + sessionId);
		String content = "Intel has reportedly delayed its launch schedule for Cedar Trail-M chips, which were initially expected to arrive as early as September. Unnamed sources associated with notebook makers have told DigiTimes the platform is now scheduled to arrive in November due to graphics driver issues that needed resolved before passing Windows 7 certification.";
		String result = spin.replaceEveryonesFavorites(content, "", QUALITY_BEST);
		System.out.println("result:" + result);
		
		String result1 = spin.identifySynonyms(content, "");
		System.out.println("result1:" + result1);
	}

}
